package es.javamyadmin.servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import es.javamyadmin.dao.TablesDAO;
import es.javamyadmin.pojo.Error;
/**
 * Clase que crea las query para modificar la estructura de una tabla
 * @author Emilio Javier Castillo Gonzalez
 * @author Hector Delgado Duran
 */
public class AlterTable extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = -6112290627586597412L;

	/**
	 * Metodo al que es llamado por el formulario y ejecuta las correspondientes modificaciones en una tabla
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int numCampos = Integer.parseInt(request.getParameter("numCampos"));
		String query = "";
		String database = request.getParameter("database");
		String user = request.getParameter("user");
		String pass = request.getParameter("pass");
		String port = request.getParameter("port");
		String host = request.getParameter("host");
		String nombreAnterior;
		String table = request.getParameter("table");
		Error error = null;
		TablesDAO tabla = new TablesDAO();
		request.setAttribute("nuevaTabla", table);
		tabla.setPath(getServletContext().getResourceAsStream("/WEB-INF/properties/mensajes.properties"));
		for(int i = 0; i<= numCampos && error == null; i++){
			nombreAnterior = request.getParameter("nombreAnterior" + i);
			if(request.getParameter("editar" + i) != null){
				query = "ALTER TABLE " + table + " change `" + nombreAnterior + "` `" + request.getParameter("nombreColum" + i) +
						"` "+ request.getParameter("tipoColum" + i);
				if(request.getParameter("nullColum" + i) == null){
					query = query + " NOT NULL";
				}
				if(request.getParameter("defaultColum" + i) != null && !request.getParameter("defaultColum" + i).trim().equals("")){
					query = query + " DEFAULT '" + request.getParameter("defaultColum" + i) + "'";
				}
				
				if(request.getParameter("extraColum" + i) != null){
					query = query + " auto_increment";
				}
				
				try {
					error =  tabla.alter(user, pass, host, port, database, table, query);
					nombreAnterior = request.getParameter("nombreColum" + i);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
			}else{
				if(request.getParameter("delete" + i) != null){
					query = "ALTER TABLE " + table + " drop " + request.getParameter("nombreAnterior" + i);
					System.out.println("<ALTERTABLE> -post- query: " + query);
					try {
						error = tabla.alter(user, pass, host, port, database, table, query);
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
				}
			}
		}
		if(error == null){
			if(request.getParameter("addTipoKey") != null && !request.getParameter("addTipoKey").equals("")){
				if(request.getParameter("addKey") != null && !request.getParameter("addKey").equals("")){
					query = "ALTER TABLE " + table +  "  ADD " + request.getParameter("addTipoKey") + "("  + request.getParameter("addKey") + ")";
					try {
						error = tabla.alter(user, pass, host, port, database, table, query);
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
				}
			}
		}
		if(error == null){
			if(request.getParameter("removeTipoKey") != null && !request.getParameter("removeTipoKey").equals("")){
				if(request.getParameter("removeKey") != null && !request.getParameter("removeKey").equals("")){
					
					query = "ALTER TABLE " + table +  "  DROP " + request.getParameter("removeTipoKey");
					if(request.getParameter("removeTipoKey").indexOf("PRI") == -1){
						query = query + " "  + request.getParameter("removeKey");
					}
					try {
						error = tabla.alter(user, pass, host, port, database, table, query);
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
				}
			}
		}
		if(error == null){
			if(request.getParameter("insertarCampo") != null){
				String nombre = null;
				String tipo = null;
				String longitud = null;
				String defaul = null;
				String atributos = null;
				String nulo = null;
				String ai = null;
				String pKey = null;
				boolean ok = false;
				String create = " alter table " + table + " add(";
				int i = 1;
				while(request.getParameter("nombreCampo" + i) != null){
					nombre = request.getParameter("nombreCampo" + i);
					tipo = request.getParameter("tipo" + i);
					longitud = request.getParameter("longitud" + i);
					defaul = request.getParameter("default" + i);
					atributos = request.getParameter("atributos" + i);
					nulo = request.getParameter("nulo" + i);
					ai = request.getParameter("a_i" + i);
					pKey = request.getParameter("atr" + i);
					if(nombre != null && !nombre.trim().equals("")){
						create = create + " " + nombre;
					}
					else{
						error = new Error("No se ha introducido el nombre de un campo de la tabla","","");
						break;
					}
					if(tipo != null &&  !tipo.trim().equals("")){
						if(longitud != null && !longitud.trim().equals("")){
							create = create + " " + tipo + "(" + longitud + ")";
						}
						else{
							create = create + " " + tipo;
						}
					}else{
						error = new Error("No se ha introducido bien el tipo de dato de un campo de la tabla","","");
						break;
					}
					if(atributos != null && !atributos.equalsIgnoreCase("BINARY")){
						create = create + " " + atributos;
					}
					if(defaul != null && !defaul.trim().equals("") && !defaul.trim().equals("null")){
						if(tipo.indexOf("int") != -1){
							create = create + " default " + defaul;
						}
						else{
							create = create + " default '" + defaul + "'";
						}
					}
					
					if(nulo != null){
						create = create + " NOT NULL";
					}
					if(pKey != null){
						create = create + " " + pKey;
					}
					
					if(ai != null){
						create = create + " auto_increment";
					}
					
					create = create + ", ";
					nombre = null;
					tipo = null;
					longitud = null;
					defaul = null;
					atributos = null;
					nulo = null;
					ai = null;
					pKey = null;
					i++;
					ok = true;
				}
				if(ok){
					create = create.substring(0 , create.length() - 2);
					create = create + ")";
					try {
						error = tabla.alter(user, pass, host, port, database, table, create);
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
				}else{
					error = new Error("No ha introducidon ningun campo nuevo","","");
				}
			}
		}
		
		if(error == null){
			if(request.getParameter("renombrarTabla") != null && request.getParameter("nuevoNombreTabla") != null){
				if(!request.getParameter("nuevoNombreTabla").trim().equals("")){
					String renombrar = "RENAME TABLE " + table + " TO " + request.getParameter("nuevoNombreTabla");
					System.out.println(renombrar);
					try {
						error = tabla.alter(user, pass, host, port, database, table, renombrar);
						request.setAttribute("nuevaTabla", request.getParameter("nuevoNombreTabla"));
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
				}else{
					error = new Error("No has introducido ningun nombre renombrar la tabla",null,null);
				}
			}
		}
		if(error != null && error.getError()!= null && !error.getError().trim().equals("")){
			System.out.println(error.getError());
			request.setAttribute("error", error.getError());
			if(error.getDescripcion()!= null && !error.getDescripcion().trim().equals("")){
				request.setAttribute("descripcion", error.getDescripcion().replace("'", "\\'"));
			}
			
		}else{
			request.setAttribute("ok", "Cambios efectuados con exito");
		}
		request.getRequestDispatcher("jsp/alter-tablas-bd.jsp?bd=" + database + "&tabla=" + table).forward(request,response);
	}

}
